from datetime import timedelta
from celery.schedules import crontab
from kombu import Queue
import pymysql
from django.conf import settings
# 注意：这里不能使用orm操作数据库，因为Django的Setting是懒加载，只有
# 用到对应的App才会加载App的模型，而此文件是在启动的时候运行，InstallApp还没有
# 被加载，因此不能使用orm模型

conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='root',
    database='task_config_pro',
    charset='utf8'
)
cursor = conn.cursor()
cron_conf_sql = """select 
                        schedule_name,
                        task_path,
                        task_name,
                        task_hour,
                        task_minute,
                        task_args,
                        task_kwargs,
                        queue_id,
                        id 
                    from schedule_cron_conf 
                    where is_active=1"""

cursor.execute(cron_conf_sql)
cron_confs = cursor.fetchall()

CELERYBEAT_SCHEDULE = {}
settings.CELERY_QUEUE = list(settings.CELERY_QUEUE)
for cron_conf in cron_confs:
    schedule_name = cron_conf[0]
    path = cron_conf[1]
    name = cron_conf[2]
    task_path = '{}.{}'.format(path, name)
    task_hour = cron_conf[3]
    task_minute = cron_conf[4]
    args = cron_conf[5]
    kwargs = cron_conf[6]
    queue_id = cron_conf[7]
    cron_id = cron_conf[8]

    queue_sql = """select
                        queue_name,
                        routing_key
                    from schedule_queue_conf
                    where id=%s"""
    cursor.execute(queue_sql, queue_id)
    queue = cursor.fetchone()

    queue_name = queue[0]
    routing_key = queue[1]

    settings.CELERY_QUEUE.append(Queue(queue_name, routing_key=routing_key))

    task_dict = {
        'task': task_path,
        'schedule': crontab(hour=task_hour, minute=task_minute),
        'args': [cron_id],
        'options': {
            'queue': queue_name,
            'routing_key': routing_key
        }
    }

    # if args:
    #     task_dict['args'] = args
    # if kwargs:
    #     task_dict['kwargs'] = kwargs

    CELERYBEAT_SCHEDULE[schedule_name] = task_dict

conn.close()
settings.CELERY_QUEUE = tuple(settings.CELERY_QUEUE)
# print(settings.CELERY_QUEUE)
# print(CELERYBEAT_SCHEDULE)
